/**
 * 
 */
package zeroj.web.action;

import java.util.List;
import java.util.ResourceBundle;

import zeroj.exceptions.ValidateException;
import zeroj.web.dispatch.ActionInfo;
import zeroj.web.dispatch.Dispatcher;
import zeroj.web.format.IFormater;
import zeroj.web.validator.IValidator;
import zeroj.web.view.wrapper.HttpRequestWrapper;

/**
 * @author LYL(lylsir at gmail dot com)
 * 
 * @since 1.0
 *
 * 2008-9-18
 */
public final class ActionHelper {

	public static String getUrl(Class<? extends IAction> actionClass) {
		
		ActionInfo info = Dispatcher.get().getActionMapper().getActionInfo(actionClass);
		return getUrl(info.getPath());
	}
	public static String getUrl(String actionPath) {
		
		StringBuilder url = new StringBuilder(Dispatcher.getRequest().getContextPath());
		return url.append("/").append(actionPath).toString();
	}
	
	public static IAction prepareAction(ActionInfo info) throws ValidateException {
		
		HttpRequestWrapper request = Dispatcher.getRequest();
		IAction action = info.getAction();
		for(String name : info.getFormats().keySet()) {
			
			String paraValue = request.getParameter(name);
			List<IValidator> validators = info.getValidates().get(name);
			for(IValidator validator : validators) {
				if(validator.isValid(paraValue))
					throw new ValidateException(name);
			}
			IFormater formater = info.getFormats().get(name);
			Object value = formater.format(paraValue);
			setActionProperty(name, value);
		}
		return action;
	}
	
	public static String getMessage(Class<?> clz, String key) {
		
		String resource = clz.getName().replaceAll("\\.", "/");
		ResourceBundle resourceBundle = ResourceBundle.getBundle(resource, Dispatcher.getRequest().getLocale());
		return resourceBundle.getString(key);
	}
	
	private static void setActionProperty(String property, Object value) {
		
		
	}
	
}
